package tsvetanv.inventory.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import tsvetanv.inventory.model.Article;
import tsvetanv.inventory.service.ArticleService;

/**
 * The <code>ArticleDeleteFormController</code> is related with processing
 * pipeline of the <b>DeleteArticle HTML Form</b>.
 * 
 * @author Tsvetan Vasilev
 * 
 */
public class ArticleDeleteFormController extends SimpleFormController {

	@Autowired
	private ArticleService articleService;

	// private static Logger logger = Logger
	// .getLogger(ArticleDeleteFormController.class);

	// --- Constructors, Getters, Setters --------------------------------------
	public ArticleDeleteFormController() {
		setCommandName("article");
		setCommandClass(Article.class);
		setFormView("/deleteForm");
		setSuccessView("redirect:/articles/home");
	}

	public ArticleService getArticleService() {
		return articleService;
	}

	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}

	// --- Methods -------------------------------------------------------------
	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		Article article = (Article) command;
		// delete article
		if (article.getId() > 0) {
			articleService.delete(article);
		}

		// prepare success view
		ModelAndView modelAndView = new ModelAndView(getSuccessView());
		modelAndView.addObject("articles", articleService.getAllArticles());
		return modelAndView;
	}
}
